import json

from asgiref.sync import sync_to_async
from channels.generic.websocket import AsyncWebsocketConsumer
from django.contrib.auth.models import AnonymousUser


class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        # 获取 room_id 和 token
        query = self.scope['query_string'].decode()
        params = dict(x.split('=') for x in query.split('&') if '=' in x)
        token = params.get('token')
        room_id = params.get('room_id')
        if not room_id or not await self.authenticate(token):
            await self.close()
            return

        self.user = self.scope["user"]
        self.room_name = f"room_{room_id}"
        await self.channel_layer.group_add(
            self.room_name,
            self.channel_name
        )
        await self.accept()

    async def authenticate(self, token, AuthToken=None):
        # 实现 JWT 验证逻辑
        try:
            user = await sync_to_async(AuthToken().authenticate_credentials)(token)
            self.scope['user'] = user
            return True
        except:
            return False

    async def new_message(self, event):
        # 增强消息广播逻辑
        message = event['message']
        await self.send(text_data=json.dumps({
            'type': 'new_message',
            'message': {
                'id': message.id,
                'sender': message.sender_id,
                'content': message.content,
                'timestamp': message.timestamp.isoformat(),
                'is_read': message.is_read
            }
        }))